﻿using System;
using System.Web.UI.HtmlControls;
using DevExpress.Web.ASPxDataView;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using NguyenHoa.Web.App_Code;

namespace NguyenHoa.Web.Pages
{
  public partial class SearchedResult : BasePage
  {
    #region Properties
    private string SearchedKey
    {
      get { return Request.QueryString["skey"]; }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      int resultNumber;
      if (!IsPostBack && !IsCallback)
      {
        LoadNews(out resultNumber);
        lblResultNumber.Text = string.Format(Resources.Strings.ResultNumber, resultNumber);
      }

      if (dvNews.IsCallback)
      {
        LoadNews(out resultNumber);
      }
    }

    protected void dvNews_DataBound(object sender, EventArgs e)
    {
      foreach (DataViewItem item in dvNews.Items)
      {
        HtmlImage imgPreview = dvNews.FindItemControl("imgPreview", item) as HtmlImage;
        Domains.News news = item.DataItem as Domains.News;
        if (news.ViewCount == null)
        {
          news.ViewCount = 0;
        }

        if (imgPreview != null)
        {
          if (news != null && !string.IsNullOrEmpty(news.ImagePath))
          {
            imgPreview.Src = "~/" + news.ImagePath;
            imgPreview.Style["Display"] = string.Empty;
            imgPreview.Attributes["onclick"] = string.Format("NewsDetailPage.aspx?t=N&id={0}&tid={1}", news.Id.ToString(), news.CategoryId.ToString());
          }
        }
      }
    }
    #endregion

    private void LoadNews(out int resultNumber)
    {
      TList<News> newsList = new NewsService().GetByHomeSearch(SearchedKey, CurrentLanguage.Id, null, null, null);
      dvNews.DataSource = newsList;
      dvNews.DataBind();

      resultNumber = newsList.Count;
    }

    public string FormatDate(object value)
    {
      return Utils.FormatDate(value);
    }
  }
}
